package org.example.groupwarehouse.controller;

import jakarta.servlet.http.HttpSession;
import org.example.groupwarehouse.entity.Admin;
import org.example.groupwarehouse.entity.Category;
import org.example.groupwarehouse.entity.Goods;
import org.example.groupwarehouse.mapper.CategoryMapper;
import org.example.groupwarehouse.mapper.GoodsMapper;
import org.example.groupwarehouse.service.CategoryService;
import org.example.groupwarehouse.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author zwy
 * @date 2025/5/14下午7:30
 * @className GoodsController
 * @se www.baidu.com
 * @verdion 1.0
 */
@Controller
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/goods/{id}")
    public String goods(Model model, @PathVariable int id) {
        //通过id拿到对应的 商品数据
        Goods good = goodsService.findById(id);
        if(good!=null){
            model.addAttribute("goods", good);
            return "goods_view";
        }else{
            //返回错误页面
            return "error";
        }

    }

    // 上传商品图片
    @PostMapping("/admin/upload/goods")
    public ResponseEntity<String> uploadAvatar(MultipartFile file) throws Exception {
        String url = goodsService.uplaodGoods(file);
        return ResponseEntity.ok(url);
    }
    //添加商品
    @PostMapping("/admin/goods/add")
    public String goodsAdd(@RequestParam String name,
                           @RequestParam String no,
                           @RequestParam Integer categoryId,
                           @RequestParam Integer stock,
                           @RequestParam BigDecimal marketPrice,
                           @RequestParam BigDecimal salePrice,
                           @RequestParam(required = false) MultipartFile file,
                           @RequestParam(required = false) String description,
                           @RequestParam(defaultValue = "N") String hottest,
                           @RequestParam(defaultValue = "N") String newest,
                           RedirectAttributes redirectAttributes) throws Exception {

        // 处理商品图片上传
        String image = "";
        if (file != null && !file.isEmpty()) {
            image = goodsService.uplaodGoods(file);
        }

        // 添加商品
        boolean result = goodsService.insertGoods(name, no, categoryId, stock, marketPrice, salePrice, image, description, hottest, newest);

        if(result) {
            redirectAttributes.addFlashAttribute("success", "商品添加成功！");
            return "redirect:/";
        } else {
            redirectAttributes.addFlashAttribute("error", "商品添加失败，请重试！");
            return "redirect:/admin/goods/add";
        }
    }
    //商品列表
    @GetMapping("/admin/goods/list")
    public String goodsList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "6") int pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) BigDecimal minPrice,
            @RequestParam(required = false) BigDecimal maxPrice,
            HttpSession session,
            Model model
    ) {
        // 权限检查
        Object loginUser = session.getAttribute("loginUser");
        if(!(loginUser instanceof Admin)){
            return "login";
        }
        // 获取所有分类（用于前端下拉菜单）
        List<Category> categories = categoryService.getAllCategories();
        model.addAttribute("categories", categories);

        // 查询商品数据
        List<Goods> goodslist = goodsService.findByPageWithCategory(
                page, pageSize, name, categoryId, minPrice, maxPrice
        );

        // 分页参数传递到前端
        long total = goodsService.countByConditions(name, categoryId, minPrice, maxPrice);
        int totalPages = (int) Math.ceil((double) total / pageSize);

        model.addAttribute("goodslist", goodslist);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);

        return "goods_list";
    }
    // 商品上架
    @GetMapping("/admin/goods/shelve")
    public String shelveGoods(@RequestParam Integer id, RedirectAttributes redirectAttributes) {
        try {
            goodsService.updateGoodsStatus(id, "0"); // 0表示在售
            redirectAttributes.addFlashAttribute("success", "商品上架成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "商品上架失败！");
        }
        return "redirect:/admin/goods/list";
    }

    // 商品下架
    @GetMapping("/admin/goods/unshelve")
    public String unshelveGoods(@RequestParam Integer id, RedirectAttributes redirectAttributes) {
        try {
            goodsService.updateGoodsStatus(id, "1"); // 1表示下架
            redirectAttributes.addFlashAttribute("success", "商品下架成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "商品下架失败！");
        }
        return "redirect:/admin/goods/list";
    }

    // 删除商品
    @GetMapping("/admin/goods/delete")
    public String deleteGoods(@RequestParam Integer id, RedirectAttributes redirectAttributes) {
        try {
            goodsService.updateGoodsStatus(id, "2"); // 2表示已删除
            redirectAttributes.addFlashAttribute("success", "商品删除成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "商品删除失败！");
        }
        return "redirect:/admin/goods/list";
    }


}
